import { Component, HostListener, ViewChild, ViewChildren } from '@angular/core';
import { CoreService } from '../../service/core.service';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import {MatChipsModule} from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import { MatInput, MatInputModule } from '@angular/material/input';
import { BreakpointObserver } from '@angular/cdk/layout';
import { ScreenService } from '../../service/screen.service';
 
@Component({
  selector: 'app-toolbar-address-cmp',
  standalone: true,
  imports: [FormsModule,CommonModule,MatChipsModule,MatButtonModule,MatIconModule,MatInputModule],
  templateUrl: './toolbar-address-cmp.component.html',
  styleUrl: './toolbar-address-cmp.component.scss'
})
export class ToolbarAddressCmpComponent {
addressWidth:number = 0; 
clickAddress($event: MouseEvent) {
  this.isEditStatus = true; 
  setTimeout(() => {
    this.addressInput.focused = true;
    this.addressInput.focus();
  }, 1);
}
 


@ViewChild('addressInput') addressInput!: MatInput; 

clickRoot() { 
   this.coreSvc.open("/");
}
clickItem(item: { index: number; name: string; }) { 
  // step 1: 获取路径
  let path ="/" + this.addressItems.slice(1,item.index+1).map(s=>s.name).join("/");  
   

  this.coreSvc.open(path);
}
 
  address = "";
  addressItems:{index:number,name:string}[] = [];
  isEditStatus = false;

  constructor(public coreSvc:CoreService,private breakpointObserver: BreakpointObserver,private screenSvc: ScreenService) { 
    coreSvc.path.subscribe(s => {
      this.address = s.path;
      this.addressItems =s.path.split("/").map((value,index)=>{
        if(index == 0) return {index,name:"全部"} 
        return {index,name:value}
      }).filter(s => s.name != "" && s.name != "undefined"); 
    });
    this.addressWidth = this.screenSvc.getInitialWidth() - 475; // 减去其他组件宽度
  }

  // 添加当前组件回车事件
  @HostListener('keydown.enter', ['$event'])
  enter(event: KeyboardEvent) {
    this.isEditStatus = false;
    if(this.address == this.coreSvc.path.value.path) {
      return;
    }
  
    this.coreSvc.open(this.address);
  }

  // 添加当前组件焦点离开事件
  @HostListener('blur', ['$event'])
  blur(event: KeyboardEvent) {
    this.isEditStatus = false;
    this.address = this.coreSvc.path.value.path;
  }
  
screenWidthSubscription: any;
   
  ngOnInit() {
    // 订阅实时宽度变化
    this.screenWidthSubscription = this.screenSvc.screenWidth$.subscribe(
      width => (this.addressWidth = width - 475) // 减去其他组件宽度
    );
  }
 
  ngOnDestroy() {
    // 取消订阅以防止内存泄漏
    if (this.screenWidthSubscription) {
      this.screenWidthSubscription.unsubscribe();
    }
  }
  
}
